package leetcode.median;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class $47_PermuteUnique {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> result = new LinkedList<>();
        if (nums.length == 0) return result;
        List<Integer> path = new LinkedList<>();
        boolean[] visited = new boolean[nums.length];
        Arrays.sort(nums);
        dfs(result, path, nums, visited);
        return result;
    }

    public void dfs(List<List<Integer>> result, List<Integer> path, int[] nums, boolean[] visited) {
        if (path.size() == nums.length) {
            result.add(new LinkedList<>(path));
            return;
        }
        for (int i = 0;i < nums.length; i++) {
            if (visited[i] || (i > 0 && nums[i] == nums[i - 1] && !visited[i - 1])) continue;
            visited[i] = true;
            path.add(nums[i]);
            dfs(result, path, nums, visited);
            path.remove(path.size() - 1);
            visited[i] = false;
        }
    }
}
